package cn.yitun.chat.yitunservernetcore.server.general.main.business.system.service.impl;

import cn.yitun.chat.yituncommonmessage.Info;
import cn.yitun.chat.yituncommonmessage.client.ClientHead;
import cn.yitun.chat.yituncommonmessage.impl.HeadImpl;
import cn.yitun.chat.yitunnetsession.session.SocketSession;
import cn.yitun.chat.yitunserverimcore.bridge.main.common.auth.box.AuthBox;
import cn.yitun.chat.yitunservercommonlib.util.cache.TokenTemporaryCache;
import cn.yitun.chat.yitunserverimcore.general.main.push.auth.AuthPush;
import cn.yitun.chat.yitunservernetcore.server.bridge.session.SocketSessionHandler;
import cn.yitun.chat.yitunservernetcore.server.general.main.business.system.service.AuthService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 
 * Date 2019-02-11 21:33:50<br>
 * Description
 * 
 * @author yitun<br>
 * @since 1.1
 */
@Service
public class SystemAuthServiceImpl implements AuthService {
	protected final Logger logger = LogManager.getLogger(this.getClass());

	@Resource
	private SocketSessionHandler socketSessionHandler;
	@Resource
	private TokenTemporaryCache tokenTemporaryCache;
	@Resource
	private AuthPush authPush;
	@Resource
	private AuthBox authBox;

	/**
	 * 服务端校验令牌
	 * @param socketSession
	 * @param clientHead
	 * @param token
	 * @return
	 */
	public Info auth(SocketSession socketSession, ClientHead clientHead, String token) {
		Info info = new Info();
		Long userId = tokenTemporaryCache.getUserId(token);
		boolean currentOffline = true;
		if (null != userId) {
			socketSession.setAuth(true);
			socketSession.setKey(userId);
			
			authBox.put(token, userId);
			putSocketSession(socketSession, clientHead);
			currentOffline = false;
		} else {
			info.addWarning(HeadImpl.code_fail, "认证失败！");
		}
		authPush.pushAuthMsg(socketSession.getKey(), currentOffline, token);
		return info;
	}

	private void putSocketSession(SocketSession socketSession, ClientHead clientHead) {
		socketSessionHandler.put(socketSession, clientHead);
	}
}
